import { createRouter, createWebHistory } from 'vue-router'
import store from "../store/index.js"

const routes = [
  // 注册界面
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/pages/Register.vue')
  },
  // 登录界面
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/pages/Login.vue')
  },
  // 布局
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/views/layout/Layout.vue'),
    redirect: '/welcome', // 重定向
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('@/views/pages/Welcome.vue')
      },
      {
        path: '/works',
        name: 'works',
        component: () => import('@/views/pages/Works.vue'),
        children: [
          {
            path: 'draw',
            name: 'Works_Draw',
            component: () => import('@/views/pages/Works_Draw.vue')
          },
          {
            path: 'write',
            name: 'Works_Write',
            component: () => import('@/views/pages/Works_Write.vue')
          },
          {
            path: 'code',
            name: 'Works_Code',
            component: () => import('@/views/pages/Works_Code.vue')
          },
          {
            path: 'life',
            name: 'Works_Life',
            component: () => import('@/views/pages/Works_Life.vue')
          }
        ]
      },
      {
        path: '/message',
        name: 'message',
        component: () => import('@/views/pages/Message.vue')
      },
      {
        path: '/aboutme',
        name: 'aboutme',
        component: () => import('@/views/pages/AboutMe.vue')
      },
      {
        path: '/uinfo',
        name: 'uinfo',
        component: () => import('@/views/pages/Uinfo.vue')
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断用户是否登录
  const uInfo = store.state.uInfo.userInfo
  if (!uInfo.username) {
    // 未登录
    if (to.path === '/login' || to.path === '/register') {
      next()
      return
    }
    next("/login")
  } else {
    next()
  }
})

export default router
